package com.ccx.coachsite.task;

import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;

import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.HttpCallBack;
import com.ccx.coachsite.http.HttpErrorDesc;
import com.ccx.coachsite.http.HttpRequest;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;

@SuppressWarnings("rawtypes")
public abstract class TaskBase extends AsyncTask<Integer, Integer, BaseResp> {

	private HttpCallBack iCall;
	protected Context mContext;
	protected String mMobile;
	protected String mUserId;
	protected int mUserType;
	protected int mTaskType;
	
	public int getTaskType() {
		return mTaskType;
	}

	public TaskBase(HttpCallBack iCall, Context context) 
	{
		this.iCall = iCall;
		this.mContext = context;
		mMobile = SharedPreferencesUtil.getValue(context, SharedKey.Shared_Mobile_Key, "");
		mUserId = SharedPreferencesUtil.getValue(context, SharedKey.Shared_UserId_Key, "");
		boolean isExport = SharedPreferencesUtil.getBoolean(mContext, SharedKey.Shared_Is_Expert);
		mUserType = isExport ? 0 : 1;
	}
	
	/*
	public TaskBase(HttpCallBack iCall) 
	{
		this.iCall = iCall;
	}
	*/
	protected abstract String genUrl(HttpRequest request);
	
	protected void onDataParse(String responseString)
	{
		
	}

	@SuppressWarnings("unchecked")
	protected void callBack(BaseResp response) {
		if (iCall != null)
			iCall.callBack(mTaskType, response, response.getResponse());
	}
	
	@Override
	protected BaseResp doInBackground(Integer... params) {
		HttpRequest request = new HttpRequest(BaseResp.class);
		BaseResp resp = new BaseResp();
		try {
			String url = genUrl(request);
			
			resp = request.execute(url);
			if (resp.isSuccess()) {
				String result = resp.getHttpResult();
				JSONObject jsonObject = new JSONObject(result);
				String status = jsonObject.getString("code");
				String desc = jsonObject.getString("desc");
				resp.setDesc(desc);
				if(status.equals("200"))
				{
					resp.setResponse(result);
					onDataParse(result);
					resp.setStatus(BaseResp.SUCCESS);
				}
				else
				{
					int statusCode = Integer.parseInt(status);
					HttpErrorDesc.setErrorDesc(statusCode, resp);
					resp.setStatus(BaseResp.ERROR);
				}
			}
		} catch (Exception e) {
			resp.setStatus(BaseResp.ERROR);
			Log.e(e.getMessage(), e);
		} finally {
			request.release();
		}

		return resp;
	}

	@Override
	protected void onPostExecute(BaseResp response) {
		if (response.getStatus() == BaseResp.ERROR) {
			if(StringUtil.isEmpty(response.getDesc()))
				response.setDesc("网络连接失败，请稍后再试...");
		}
		callBack(response);
	};

}
